import easyDAO.SqlDispatch;
import models.*;
import tools.ReadProperties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;

/**
 * Created by yangxianming on 2018/1/16.
 * 设备数据上传测试
 */
@WebServlet(name = "changePW", urlPatterns = {"/changePW/*"}, loadOnStartup = 2)
public class ChangePW extends HttpServlet {
    MyConfig myConfig = new MyConfig();
    public void init(ServletConfig config) throws ServletException {
        ReadProperties readProperties = new ReadProperties(config.getServletContext().getRealPath("/"));
        myConfig.setPropertiesConfig(readProperties);
        myConfig.setSplitMark();
        myConfig.setUser(new User());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //start
        long start = new Date().getTime();

        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String returnInfo = "";

        //首字母大写
//        char[] cs = request.getPathInfo().substring(1).toCharArray();
//        cs[0] -= 32;

        Class<?> action;
        try {
            ReturnJson rj = new ReturnJson();
            HttpSession sh = request.getSession();
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String newPassword = request.getParameter("newPassword");
            //guest无法改自己的密码
            if (username.equals("guest")){
                rj.setErrorMsg("guest不能改密码");
                rj.setApiStatus(0);
                out.print(rj.toString());
                return;
            }
            //校验cookie，只能自己改自己的
            boolean isOwner = true;
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie: cookies){
                if (Objects.equals(cookie.getName(), "JSESSIONID")){
                    String comeCook = cookie.getValue();
                    User user = (User)sh.getAttribute(comeCook);
                    String regUsername = user.getUsername();
                    if (!Objects.equals(regUsername, username)){
                        rj.setErrorMsg("不要尝试修改别人的密码");
                        rj.setApiStatus(0);
                        out.print(rj.toString());
                        return;
                    }
                }
            }

            //拿到用户数据
            SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
            String sql1 = "SELECT username, password,power FROM `user` WHERE username = \""+username+"\"";
            SqlReturnModel srm = sqlDispatch.selectWord(sql1);
            //验证密码
            if (checkUser(srm, password)){
                //更新密码
                String md5PW =  Md5.md5PlusSalt(newPassword);
                String set = " SET password = '"+md5PW+"' ";
                String where = " WHERE username='"+username+"' ";
                String sql2 = "UPDATE `user` " + set + where;
                srm = sqlDispatch.update(sql2);
                if (srm.getIsSuccess()){
                    rj.setResult("修改成功");
                }else {
                    rj.setResult(0, null, srm.getFailingReason());
                    out.print(rj.toString());
                    return;
                }
            }else {
                rj.setErrorMsg("密码错误");
                rj.setApiStatus(0);
                out.print(rj.toString());
                return;
            }
            returnInfo = rj.toString();

        }catch (Exception e){
            e.printStackTrace();
        }

        //end
        long end = new Date().getTime();
        System.out.println(request.getRequestURI() + "; run time: " + (end-start) + "ms");

        out.print(returnInfo);
    }

    @Override
    public void destroy()
    {
        // 什么也不做
    }

    private boolean checkUser(SqlReturnModel srm, String passWord){
        ArrayList<ArrayList<String>> userInfo = srm.getSelectReturnData();
        if (userInfo.size() == 0){
            //用户名没有退出
            return false;
        }
        if (!Objects.equals(Md5.md5PlusSalt(passWord), userInfo.get(0).get(1))){
            //密码不对退出
            return false;
        }
        return true;
    }
}
